<template>
    <a-modal v-model:open="visible" title="成分股" :keyboard="false" :maskClosable="false" @ok="handleOk" width="61%">
        <div>

          <div v-show="!stockCode">
            <a-input-search v-model:value="code" style="width: 240px" :loading="loading" @search="onSearch"/>
          </div>



          <div v-show="formState.code!==''">

            <div class="pd-b-s pd-t-s">
              <h2>{{formState.name}} <a-tag color="red" style="vertical-align: text-top;">{{ formState.type }}</a-tag></h2>
              <h5 class="font-light font-thin">{{formState.secucode}}</h5>
            </div>

            <table class="bsl-table" cellspacing="0" cellpadding="0" style="width: 100%;">
              <thead>
                <tr>
                  <th>{{ formState.reportDate }}</th>
                  <th>主营构成</th>
                  <th>主营收入</th>
                  <th>收入比例</th>
                  <th>主营成本</th>
                  <th>成本比例</th>
                  <th>主营利润</th>
                  <th>利润比例</th>
                  <th>毛利率</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="(b,bi) in formState.business" :key="bi">
                  <td :rowspan="b.rowspan" v-if="b.rowspan">{{ translateOp(b["MAINOP_TYPE"]) }}</td>
                  <td>{{ b["ITEM_NAME"] }}</td>
                  <td>{{ convertToChineseUnit(b["MAIN_BUSINESS_INCOME"]) }}</td>
                  <td>{{ convertToPercentage(b["MBI_RATIO"]) }}</td>
                  <td>{{ convertToChineseUnit(b["MAIN_BUSINESS_COST"]) }}</td>
                  <td>{{ convertToPercentage(b["MBC_RATIO"]) }}</td>
                  <td>{{ convertToChineseUnit(b["MAIN_BUSINESS_RPOFIT"])  }}</td>
                  <td>{{ convertToPercentage(b["MBR_RATIO"]) }}</td>
                  <td>{{ convertToPercentage(b["GROSS_RPOFIT_RATIO"]) }}</td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>

      <template #footer>
        <a-button @click="visible=false">取消</a-button>
        <a-button v-show="!stockCode" type="primary" :loading="loading" @click="handleOk">确认</a-button>
      </template>

    </a-modal>
</template>

<script>

import { Modal,InputSearch,Tag } from 'ant-design-vue';
import { searchStock,stockCreate,getStock } from "@/api/stock";
import {convertToChineseUnit} from "@/common/utils";


// 为每个项目添加rowspan属性
function addRowspanByMainopType(data) {

  data = data.sort((a, b) => {
    // 将MAINOP_TYPE转换为数字进行比较
    return Number(a.MAINOP_TYPE) - Number(b.MAINOP_TYPE);
  });

  // 先按MAINOP_TYPE分组统计数量
  const typeCounts = data.reduce((acc, item) => {
    const type = item.MAINOP_TYPE;
    acc[type] = (acc[type] || 0) + 1;
    return acc;
  }, {});

  // 跟踪每个类型已处理的数量
  const processedCount = {};

  // 为每个项目添加rowspan属性
  return data.map(item => {
    const type = item.MAINOP_TYPE;
    processedCount[type] = (processedCount[type] || 0) + 1;
    return {
      ...item,
      rowspan: processedCount[type] === 1 ? typeCounts[type] : 0
    };
  });
}

function resetForm(){
  return {
    code: "",
    business:"",
    description:"",
    eval:"",
    name:"",
    reportDate:"",
    secucode:"",
    type:""
  }
}


export default{
    components: {
        AModal: Modal,
        AInputSearch: InputSearch,
        ATag: Tag
    },
    props: ["boardId"],
    data(){
        return {
            loading: false,
            visible: false,
            code: "",
            stockCode: null,
            formState: resetForm()
        }
    },
    methods: {
        convertToChineseUnit,
        convertToPercentage(num){
          if (num){
            return (num * 100).toFixed(2) + '%';
          } else {
            return ;
          }

        },
        translateOp(type){
          if(type == "1"){
            return "按行业分类";
          } else if (type == "2"){
            return "按产品分类";
          } else if (type == "3"){
            return "按地区分类";
          }
          return "未知"+type
        },
        open(item){
            if(item){
              this.stockCode = item.stockCode;
              getStock(this.stockCode).then((res) => {
                this.formState = {
                  ...res.data,
                  business: addRowspanByMainopType(JSON.parse(res.data.business))
                }
              })
            } else {
              this.stockCode = null;
              this.code = "";
              this.formState = resetForm();
            }
            this.visible = true;
        },
        onSearch(){
            this.loading = true;
            searchStock(this.code).then(res=>{
              this.loading = false;
              if (res.data.code!==''){
                this.formState = {
                  ...res.data,
                  business: addRowspanByMainopType(JSON.parse(res.data.business))
                }
              } else {
                this.$message.error("没有结果！")
              }

            })
        },
        handleOk(){

          if (this.formState.code!==""){
            stockCreate({
              ...this.formState,
              business: JSON.stringify(this.formState.business),
              boardId: this.boardId
            }).then(res=>{
              this.visible = false;
              this.$emit("success")
            })
          } else {
            this.$message.warn("请先搜索股票代码")
          }

        }
    }

}

</script>
